package com.hbnu.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbnu.system.config.BaseException;
import com.hbnu.system.mapper.ConstructionfileMapper;
import com.hbnu.system.model.entity.Constructionfile;
import com.hbnu.system.service.IConstructionfileService;
import com.hbnu.system.utils.FileUploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.BindException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2023-05-16
 */
@Service
public class ConstructionfileServiceImpl extends ServiceImpl<ConstructionfileMapper, Constructionfile> implements IConstructionfileService {
    @Autowired
    FileUploadUtil fileUploadUtil;

    @Override
    public boolean addConstructionfile(Constructionfile constructionfile) {
        constructionfile.setFiledate(LocalDateTime.now());
        return baseMapper.insert(constructionfile)==1;
    }

    @Override
    public Constructionfile getConstructionfile(String id) {
        Constructionfile constructionfile = super.getOne(Wrappers.lambdaQuery(Constructionfile.class)
                .eq(Constructionfile::getConstructionID, id));
        if(Objects.isNull(constructionfile)){
            throw new BaseException("文件编号异常!未查找到该文件信息");
        }
        return constructionfile;
    }

    @Override
    public List<Constructionfile> pageConstructionfile(String id) {
        List<Constructionfile> constructionfileList = baseMapper.selectList(Wrappers.lambdaQuery(Constructionfile.class)
                .eq(Constructionfile::getConstructionID,id));
        return constructionfileList;
    }


    //还需要删除文件信息
    @Override
    public boolean deletConstructionfile(String id) throws IOException {
        Constructionfile one = super.getOne(Wrappers.lambdaQuery(Constructionfile.class)
                .eq(Constructionfile::getFileid, id));
        if (Objects.isNull(one)){
            throw new BaseException("文件编号有误!");
        }

        boolean delete = fileUploadUtil.delete(one.getFileurl());
        if(!delete){
            throw new BindException("附件删除失败");
        }
        return baseMapper.deleteById(id) == 1;
    }

    @Override
    public boolean updateConstructionfile(Constructionfile constructionfile) {
        return baseMapper.updateById(constructionfile)==1;
    }
}
